<?php
namespace application\admin\panels;
use application\utilities\Utility;

class configure extends panel {
	public $name = 'Configure';
	protected $ContentType;
	protected $deleted;
	
	public function __construct() {
		$contentType = $_REQUEST['type'];
		$this->ContentType = new \application\models\ContentType($contentType);
		
	}
	
	public function title() {
		return 'Configure / ' . $this->ContentType->getPlural();
	}
	
	public function deleteContentType() {
		$this->ContentType->delete();
	}
	
	public function handleData() {
		if($_REQUEST['update_settings']) {
			foreach($_REQUEST as $field=>$value) {
				$functionName = 'set'.(Utility::toCamelCase($field));
				$this->ContentType->$functionName($value);
			}
			$this->mergeMessages($this->ContentType->save());
		}
		echo json_encode($this->messages);
	}
	
	
	public function sidebar() {
		return array(
			array(
				'title'=>'Start',
				'sectionID'=>'start'
			),
			array(
				'title'=>'Reading',
				'sectionID'=>'reading'
			),
			array(
				'title'=>'Data',
				'sectionID'=>'data'
			),
			array(
				'title'=>'User Feedback',
				'sectionID'=>'feedback'
			),
			array(
				'title'=>'User Interactions',
				'sectionID'=>'interactions'
			),
			array(
				'title'=>'Permalink Settings',
				'sectionID'=>'permalinks'
			),
			array(
				'title'=>'Content Relations',
				'sectionID'=>'relations'
			),
			array(
				'title'=>'Tags',
				'sectionID'=>'tags'
			)
		);
	}
	
	public function editTag() {
		ob_start();
		$editTag = new \application\models\Tag($_REQUEST['tag']);
		$type = $_REQUEST['type'];
		if($editTag->getType() == 'group') :?>
		<form>
			<input type="hidden" name="tag_id" value="<?=$_REQUEST['tag']?>"/>
			<ul class="form-fields">
				<li>
					<label>Group Name</label>
					<input type="text" class="big-text wide" value="<?=$editTag->getTitle()?>" name="title"/>
				</li>
				<li>
					<label>Group Permalink</label>
					<input type="text" class="big-text wide" value="<?=$editTag->getPermalink()?>" name="permalink"/>
				</li>
				<li>
					<label><input type="radio" checked="checked" name="order" value="name"/> Order tags alphabetically</label>
					<label><input type="radio" <?=($editTag->getOrder() == 'custom') ? 'checked="checked"' : ''?> name="order" value="custom"/> Order tags as by tag order (defined per tag)</label>
				</li>
				<li>
					<p>Note that deleting this group will delete all tags in the group as well.</p>
				</li>
			</ul>
		</form>
		<?php else : ?>
		<form>
			<input type="hidden" name="tag_id" value="<?=$_REQUEST['tag']?>"/>
			<ul class="form-fields">
				<li>
					<label>Tag Name</label>
					<input type="text" value="<?=$editTag->getTitle()?>" name="tag_title"/>
				</li>
				<li>
					<label>Tag Permalink</label>
					<input type="text" value="<?=$editTag->getPermalink()?>" name="tag_permalink"/>
				</li>
				<li>
					<label>Order</label>
					<input type="text" class="thin" name="tag_order" value="<?=$editTag->getOrder()?>"/>
				</li>
				<li>
					<?php 
					$results = DB()->getResults("SELECT `tag_title`, `tag_id` FROM `cn_tags` WHERE `tag_type`='group' AND `tag_content_type`='$type'");?>
					<label>Tag Group</label>
					<select name="tag_group" id="tag-group-select">
						<option value="">Select a Group</option>
						
						<?php foreach($results as $tag) : ?>
						<option <?php if($editTag->getGroup() == $tag->tag_id) echo 'selected="selected"';?> value="<?=$tag->tag_id?>"><?=$tag->tag_title?></option>
						<?php endforeach;?>
					</select>
				</li>
			</ul>
		</form>
		
		<?php endif;
		$content = ob_get_clean();
		echo json_encode(array('content'=>$content));
	}
	
	public function addInteraction() {
		$interaction = new \application\models\Interaction;
		
		$interaction->create(array(
			'name'=>$_REQUEST['name'],
			'contentType'=>$_REQUEST['type'],
			'onText'=>$_REQUEST['onText'],
			'offText'=>$_REQUEST['offText'],
			'onAlert'=>$_REQUEST['onAlert'],
			'offAlert'=>$_REQUEST['offAlert']
		));
		$interaction->save();
		
		ob_start();
		$this->manageInteractionsTable();
		$table = ob_get_clean();
		echo json_encode(array('table'=>$table));
		exit();
	}
	
	public function saveInteraction() {
		
		$interaction = new \application\models\Interaction($_REQUEST['interaction']);
		
		if($_REQUEST['interaction_delete']) {
			$interaction->delete();
			$this->addMessage('success', 'Interaction deleted successfully.');
			
		}
		else {
			$interaction->setName($_REQUEST['name']);
			$interaction->setOnText($_REQUEST['onText']);
			$interaction->setOnAlert($_REQUEST['onAlert']);
			$interaction->setOffText($_REQUEST['offText']);
			$interaction->setOffAlert($_REQUEST['offAlert']);
			$interaction->save();
		}
		
		ob_start();
		$this->manageInteractionsTable();
		$table = ob_get_clean();
		echo json_encode(array('table'=>$table));
		exit();
		
	}
	
	public function editInteraction() {
		ob_start();
		$interaction = new \application\models\Interaction($_REQUEST['id']);
		$type = $_REQUEST['type'];
		?>
		<form>
			<input type="hidden" name="interaction" value="<?=$_REQUEST['id']?>"/>
			<ul class="form-fields">
				<li>
					<label>Interaction Name</label>
					<input type="text" class="big-text wide" value="<?=$interaction->getName()?>" name="name"/>
				</li>
				<li>
					<label>On Text</label>
					<input type="text" class="big-text wide" value="<?=$interaction->getOnText()?>" name="onText"/>
				</li>
				<li>
					<label>On Alert</label>
					<input type="text" class="big-text wide" value="<?=$interaction->getOnAlert()?>" name="onAlert"/>
				</li>
				<li>
					<label>Off Text</label>
					<input type="text" class="big-text wide" value="<?=$interaction->getOffText()?>" name="offText"/>
				</li>
				<li>
					<label>Off Alert</label>
					<input type="text" class="big-text wide" value="<?=$interaction->getOffAlert()?>" name="offAlert"/>
				</li>
			</ul>
		</form>
		<?php
		$content = ob_get_clean();
		echo json_encode(array('content'=>$content));
	}
	
	public function editField() {
		$field = getQueryVar('field');
		$row = DB()->getRow("SELECT `cf_data_type`, `cf_column` FROM `cn_content_fields` WHERE `cf_id`='$field'");
		$dataType = $row->cf_data_type;
		ob_start();
		?>
		<form>
		<?php
		
			
		
		$dataType = 'application\\datatypes\\'.$dataType;
		$dataType::editForm(new \application\models\ContentField($field));
		?>
		</form>
		<?php
		$content = ob_get_clean();
		$return = array('content'=>$content);
		if(in_array($row->cf_column, array('content_id', 'content_title', 'content_content', 'content_status', 'content_author', 'content_timestamp', 'content_parent'))) {
			$return['hide_delete'] = TRUE;
		}
		echo json_encode($return);
		exit();
	}
	
	public function newTag() {
		$tag = new \application\models\Tag;
		$tag->create(array(
			'title'=>$_REQUEST['tag_title'],
			'group'=>$_REQUEST['tag_group'],
			'type'=>$_REQUEST['tag_type'],
			'permalink'=>$_REQUEST['tag_permalink'],
			'order'=>$_REQUEST['tag_order'],
			'contentType'=>$_REQUEST['type']
		));
		
		$save = $tag->save();
		if($save['status'] == 'error') {
			foreach($save['errors'] as $error) {
				$this->addMessage('error', $error);
			}
		}
		else {
			$this->addMessage('success', 'Tag created successfully.');
			
			
		} 
		ob_start();
		$this->manageTagsTable();
		$table = ob_get_clean();
		echo json_encode(array('messages'=>$this->messages, 'id'=>$tag->getId(), 'title'=>$tag->getTitle(), 'table'=>$table));
	}
	
	protected function manageTagsTable() {
		$contentType = $this->ContentType->getId();
		?>
		<table id="manage-tags-table" class="admin-table" width="100%">
			<thead>
				<tr>
					<th width="100%">Name</th>
				</tr>
			</thead>
			<tbody>
				<?php $style = '';?>
				<?php $groups = DB()->getResults("SELECT * FROM `cn_tags` WHERE `tag_content_type`='$contentType' AND `tag_type`='group' ORDER BY `tag_title`");
				foreach($groups as $group) : 
				
				?>
				<tr class="table-inner-header">
					
					<td><a href="<?=$group->tag_id?>"><?=$group->tag_title?></a></td>
				</tr>
				<?php $tags = DB()->getResults("SELECT * FROM `cn_tags` WHERE `tag_content_type`='$contentType' AND `tag_group`='$group->tag_id' ORDER BY `tag_title`");
				$style = '';
				foreach($tags as $tag) : ?>
				<tr<?=$style?>>
					
					<td><a href="<?=$tag->tag_id?>"><?=$tag->tag_title?></a></td>
				</tr>
				<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
				<?php endforeach;endforeach;?>
			</tbody>
		</table>
		<?php
	}
	
	public function saveTag() {
		$tag = new \application\models\Tag($_REQUEST['tag_id']);
			
		if($_REQUEST['tag_delete']) {
			$tag->delete();
			$this->addMessage('success', 'Tag deleted successfully.');
			
		}
		else {
			$tag->setTitle($_REQUEST['title']);
			$tag->setGroup($_REQUEST['group']);
			$tag->setPermalink($_REQUEST['permalink']);
			$tag->setOrder($_REQUEST['order']);
			
			$save = $tag->save();
			$this->addMessage('success', 'Field updated successfully');
		}
		
		ob_start();
		$this->manageTagsTable();
		$table = ob_get_clean();
		echo json_encode(array('messages'=>$this->messages, 'table'=>$table));
	}
	
	public function saveField() {
		$field = new \application\models\ContentField($_REQUEST['field_id']);
			
		if($_REQUEST['field_delete']) {
			$field->delete();
			$this->addMessage('success', 'Field deleted successfully.');
			
		}
		else {
			$field->setDisplayName($_REQUEST['field_display_name']);
			$field->setRequired($_REQUEST['field_required']);
			$field->setShow($_REQUEST['field_show']);
			$field->setDescription($_REQUEST['field_description']);
			$field->setAux($_REQUEST['field_aux']);
			$field->setShow($_REQUEST['field_show']);
			$field->save();
			
			// Get meta
			foreach($_REQUEST as $key=>$value) {
				if(substr($key, 0, 5) == 'meta_') {
					setFieldMetaData($field->getId(), substr($key, 5), $value);
				}
			}	
			$this->addMessage('success', 'Field updated successfully');
		}
		ob_start();
		$this->manageDataTable();
		$table = ob_get_clean();
		echo json_encode(array('messages'=>$this->messages, 'table'=>$table));
	}
	
	public function newField() {
		$field = new \application\models\ContentField;
		if($_REQUEST['type']) {
			$type = $_REQUEST['type'];
		}
		else {
			$type = 'user';
		}
		if($_REQUEST['field_display_name'] && $_REQUEST['field_data_type']) {
			$field->create(array(
				'displayName'=>$_REQUEST['field_display_name'],
				'dataType'=>$_REQUEST['field_data_type'],
				'required'=>$_REQUEST['field_required'],
				'description'=>$_REQUEST['field_description'],
				'default'=>$_REQUEST['field_default'],
				'aux'=>$_REQUEST['field_aux'],
				'contentType'=>$type
			));
			$field->add();
			$this->addMessage('success', 'Field added successfully.');
			$ID = $field->getId();
			
		}
		else {
			$this->addMessage('error', 'Your field must have a name and data type.');
		}
		
		ob_start();
		$this->manageDataTable();
		$table = ob_get_clean();
		
		echo json_encode(array('messages'=>$this->messages, 'table'=>$table));
	}
	
	protected function manageDataTable() {
		?>
		<table id="manage-data-table" class="admin-table" width="100%">
			<thead>
				<tr>
					<th width="50%">Name</th>
					<th width="50%">Type</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<th width="50%">Name</th>
					<th width="50%">Type</th>
				</tr>
			</tfoot>
			<tbody>
				<?php $style = '';?>
				<?php $results = DB()->getResults("SELECT * FROM `cn_content_fields` WHERE `cf_content_type`='".getQueryVar('type')."' ORDER BY `cf_display_name`");
				foreach($results as $result) : 
				
				?>
				
				<tr<?=$style?> id="field-row-<?=$result->cf_id?>">
					<?php if(in_array($result->cf_data_type, array('Permalink', 'ID', 'Status', 'Author', 'Timestamp', 'Level', 'Password'))): ?>
						<td class="display-name"><?=$result->cf_display_name?></td>
					<?php else : ?>
						<td class="display-name"><a href="<?=$result->cf_id?>"><?=$result->cf_display_name?></a></td>
					<?php endif;?>
					
					<td><span class="tooltip"><?=\application\utilities\Utility::camelCaseToNormal($result->cf_data_type)?></span><div class="tooltip-content">
			<div class="tooltip-arrow"></div>
			<div class="tooltip-inner">
			<h3><?=\application\utilities\Utility::camelCaseToNormal($result->cf_data_type)?></h3>
			<?php $class = "\\application\\datatypes\\".$result->cf_data_type;
			$class::typeDescription();?>
			</div>
		</div></td>
				</tr>
				<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
				<?php endforeach;?>
			</tbody>
		</table>
		<?php
	}
	
	public function manageInteractionsTable() {
		?>
		<table id="manage-interactions-table" class="admin-table" width="100%">
			<thead>
				<tr>
					<th width="100%">Name</th>
				</tr>
			</thead>
			<tbody>
				<?php $style = '';?>
				<?php $results = DB()->getResults("SELECT * FROM `cn_content_interactions` WHERE `ci_content_type`='".$_REQUEST['type']."'");
				foreach($results as $result) : 
				
				?>
				<tr<?=$style?>>
					
					<td><a href="<?=$result->ci_id?>"><?=$result->ci_name?></a></td>
				</tr>
				<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
				<?php endforeach;?>
			</tbody>
		</table>
		<?php
	}
	
	public function display() {
		?>
		<script type="text/javascript">
			$('#add-tag-group, #add-tag').click(function(e) {
				var id = $(this).attr('id');
				
				e.preventDefault();
				
				// Get data
				var formData = concerto.admin.getFormValues($(this).parent('li').parent('ul'));
				
				if(!formData.tag_title) {
					torchd.ui.showDialog({
						title:'Error',
						type:'alert',
						size:'small',
						message:'Please choose a name.'
					});
					return;
				}
				else if(id == 'add-tag' && !formData.tag_group) {
					torchd.ui.showDialog({
						title:'Error',
						type:'alert',
						size:'small',
						message:'Please select a tag group for your tag.<br />If there are none available, you must create one.'
					});
					return;
				}
				$.ajax({
					url:concerto.admin.rootUrl + 'admin/?display=configure&mode=ajax-method&method=newTag&type=' + <?=$this->ContentType->getId()?>,
					data:formData,
					type:'POST',
					dataType:'json',
					beforeSend:function() {
						torchd.ui.showDialog({
							title:'Adding...',
							type:'ajax-loader'
						});
					},
					error:function(a,b,c) {
						alert(b);
					},
					success:function(response) {
						torchd.ui.closeDialog('Adding...');
						$('#' + id).parent('li').parent('ul').find('input,textarea,select').not('[type="submit"]').not('[type="hidden"]').val('');
						
						if(id == 'add-tag-group') {
							$('#tag-group-select').append('<option value="'+response.id+'">'+response.title+'</option>');
						}
						$('#manage-tags-table').replaceWith(response.table);
						
					}
				});
			});	
			
			$('.form-tab').live('click', function(e) {
				e.preventDefault();
				if(!$(this).hasClass('selected')) {
					var id = $(this).attr('id');
					var tabId = id.toString().replace('-button', '');
					var tab = $('#' + tabId);
					var tabClass = tab.attr('class');
					$('.'+tabClass).hide();
					tab.show();
					$(this).parent().children('.form-tab').removeClass('selected');
					$(this).addClass('selected');
					
				}
			});
			$('#single-permalink-structure-bank').sortable({
				connectWith:'#single-permalink-structure',
				forcePlaceholderSize:true,
				stop:function() {
					if(!$('#single-permalink-structure').children('.can-sort').length) {
						$('#single-permalink-structure').prepend('<li class="permalink-structure-blank can-sort"></li>');
					}
					else {
						$('#single-permalink-structure').children('.permalink-structure-blank').remove();
					}
				}
			});
			$('#single-permalink-structure').sortable({
				connectWith:'#single-permalink-structure-bank',
				items:'li.can-sort',
				stop:function() {
					if(!$('#single-permalink-structure').children('.can-sort').length) {
						$('#single-permalink-structure').prepend('<li class="permalink-structure-blank can-sort"></li>');
					}
					else {
						$('#single-permalink-structure').children('.permalink-structure-blank').remove();
					}
				},
				forcePlaceholderSize:true
			});
			
			$('#browsing-permalink-structure-bank').sortable({
				connectWith:'#browsing-permalink-structure',
				forcePlaceholderSize:true,
				stop:function() {
					if(!$('#browsing-permalink-structure').children('.can-sort').length) {
						$('#browsing-permalink-structure').prepend('<li class="permalink-structure-blank can-sort"></li>');
					}
					else {
						$('#browsing-permalink-structure').children('.permalink-structure-blank').remove();
					}
				}
			});
			$('#browsing-permalink-structure').sortable({
				connectWith:'#browsing-permalink-structure-bank',
				items:'li.can-sort',
				stop:function() {
					if(!$('#browsing-permalink-structure').children('.can-sort').length) {
						$('#browsing-permalink-structure').prepend('<li class="permalink-structure-blank can-sort"></li>');
					}
					else {
						$('#browsing-permalink-structure').children('.permalink-structure-blank').remove();
					}
				},
				forcePlaceholderSize:true
			});
			
			$('.tag-group-permalink-structure').each(function() {
				var connectId = '#'+$(this).attr('id') + '-bank';
				var selfId = '#'+$(this).attr('id');
				$(this).sortable({
					connectWith:connectId,
					items:'li.can-sort',
					stop:function() {	
						if(!$(selfId).children('.can-sort').length) {
							$(selfId).prepend('<li class="permalink-structure-blank can-sort"></li>');
						}
						else {
							$(selfId).children('.permalink-structure-blank').remove();
						}
					},
					forcePlaceholderSize:true
				});
				
			});
			$('.tag-group-permalink-structure-bank').each(function() {
				var connectId = '#'+$(this).attr('id').replace('-bank', '')
				$(this).sortable({
					connectWith:connectId,
					items:'li.can-sort',
					stop:function() {
						if(!$(connectId).children('.can-sort').length) {
							$(connectId).prepend('<li class="permalink-structure-blank can-sort"></li>');
						}
						else {
							$(connectId).children('.permalink-structure-blank').remove();
						}
					},
					forcePlaceholderSize:true
				});
				
			});
			$('#add-field').click(function(e) {
				e.preventDefault();
				var form = {
					field_display_name:$('input[name="field_display_name"]').val(),
					field_description:$('textarea[name="field_description"]').html(),
					field_data_type:$('select[name="field_data_type"]').val(),
					required:$('input[name="required"]').val()
				};
				/**concerto.admin.postData({
					url:'mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=newField',
					dataType:'json',
					data:form,
					loadingText:'Adding Field...',
					success:function(response) {
						$('#add-field').parent('li').parent('ul').find('input,textarea,select').val('');
						$('#manage-data-table').replaceWith(response.table);
					}
					
				});*/
				$.ajax({
					url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=newField',
					type:'POST',
					error:function(a,b,c) {
						alert(b);
					},
					data:form,
					dataType:'json',
					beforeSend:function() {
						torchd.ui.showDialog({
							title:'Adding Field...',
							type:'ajax-loader'
						});
					},
					success:function(response) {
						torchd.ui.closeDialog('Adding Field...');
						$('#add-field').parent('li').parent('ul').find('input,textarea,select').val('');
						$('#manage-data-table').replaceWith(response.table);
							
					}
				});
			});	
			
			$('#add-interaction-button').click(function(e) {
				e.preventDefault();
				var form = {
					onText:$('input[name="interaction_on_text"]').val(),
					offText:$('input[name="interaction_off_text"]').val(),
					onAlert:$('input[name="interaction_on_alert"]').val(),
					offAlert:$('input[name="interaction_off_alert"]').val(),
					name:$('input[name="interaction_name"]').val()
				};
				concerto.admin.postData({
					url:'display=configure&type=<?=$this->ContentType->getId()?>&mode=ajax-method&method=addInteraction',
					dataType:'json',
					data:form,
					loadingText:'Adding Interaction...',
					success:function(response) {
						$('#manage-interactions-table').replaceWith(response.table);
					}
					
				});
			});	
			
			$('.permalink-edit-link').live('click', function(e) {
				var li = $(this).parent('li');
				e.preventDefault();
				var editForm = $(this).parent().children('.permalink-edit-form')
				var html = editForm.html();
				torchd.ui.showDialog({
					title:'Edit Permalink Structure: <b>' + $(this).attr('data-structure-name')+'</b>',
					type:'confirm',
					content:html,
					onSubmit:function(data) {
						// Set the data and copy it all to the edit form so it will show up correctly if they click edit again
						editForm.find('input').attr('checked', false);
						editForm.find('select').children('option').attr('selected', 'false');
						data.find('input,select,textarea').each(function() {
							switch($(this).get(0).tagName) {
								case 'INPUT':
									if($(this).attr('type') == 'radio') {
										if($(this).is(':checked')) {
											li.attr('data-'+$(this).attr('name'), $(this).val());
											var val = $(this).val();
											editForm.find('input[name="'+$(this).attr('name')+'"]').each(function() {
												if($(this).val() == val) {
													$(this).attr('checked', 'checked');
												}
											});
										}
										
									}
									else {
										li.attr('data-'+$(this).attr('name'), $(this).val());
										editForm.find('input[name="' + $(this).attr('name') + '"]').val($(this).val());
									}
									break;
								case 'TEXTAREA':
									li.attr('data-'+$(this).attr('name'), $(this).html());
									editForm.find('textarea[name="' + $(this).attr('name') + '"]').html($(this).html());
									break;
								case 'SELECT':
									li.attr('data-'+$(this).attr('name'), $(this).children(':selected').val());
									editForm.find('select[name="' + $(this).attr('name') + '"]').val($(this).val());
									break;
							}
						});
					}
				});
			});
			$('#manage-tags-table a').live('click', function(e) {
				var tag = $(this).attr('href');
				var title = $(this).html();
				e.preventDefault();
				torchd.ui.showDialog({
					title:'Edit Tag: ' + title, 
					type:'ajax',
					ajaxUrl:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=editTag&tag='+tag,
					buttons:[
						{
							id:'submit',
							title:'Submit',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								$.ajax({
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveTag',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-tags-table').replaceWith(response.table);
										dialog.close();
										
									}
								});
							}
						},
						{
							id:'cancel',
							title:'Cancel',
							clickAction:function() {
								$(this).data('dialog').close();
							}
						},
						{
							id:'delete',
							title:'Delete',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								form.tag_delete = true;
								$.ajax({
								
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveTag',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-tags-table').replaceWith(response.table);

										dialog.close();
										
									}
								});
							}
						}
					]
				});
			});
			$('#manage-data-table a').live('click', function(e) {
				var field = $(this).attr('href');
				var title = $(this).html();
				e.preventDefault();
				torchd.ui.showDialog({
					title:'Edit Data Field: ' + title, 
					type:'ajax',
					ajaxUrl:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=editField&field='+field,
					buttons:[
						{
							id:'submit',
							title:'Submit',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								$.ajax({
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveField',
									type:'POST',
									dataType:'json',
									data:form,
									error:function(a,b,c) {
										alert(b);
									},
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-data-table').replaceWith(response.table);
										dialog.close();
										
									}
								});
							}
						},
						{
							id:'cancel',
							title:'Cancel',
							clickAction:function() {
								$(this).data('dialog').close();
							}
						},
						{
							id:'delete',
							title:'Delete Field',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								form.field_delete = true;
								$.ajax({
								
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveField',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-data-table').replaceWith(response.table);
										
										dialog.close();
										
									}
								});
							}
						}
					]
				});
			});
			
			$('#manage-interactions-table a').live('click', function(e) {
				var interaction = $(this).attr('href');
				var title = $(this).html();
				e.preventDefault();
				torchd.ui.showDialog({
					title:'Edit Interaction: ' + title, 
					type:'ajax',
					ajaxUrl:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=editInteraction&id='+interaction,
					buttons:[
						{
							id:'submit',
							title:'Submit',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								$.ajax({
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveInteraction',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-interactions-table').replaceWith(response.table);
										dialog.close();
										
									}
								});
							}
						},
						{
							id:'cancel',
							title:'Cancel',
							clickAction:function() {
								$(this).data('dialog').close();
							}
						},
						{
							id:'delete',
							title:'Delete',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								form.interaction_delete = true;
								$.ajax({
								
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure&type=<?=$this->ContentType->getId()?>&method=saveInteraction',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-interactions-table').replaceWith(response.table);

										dialog.close();
										
									}
								});
							}
						}
					]
				});
			});
		</script>
		<form method="post">
			<section id="start">
				<div class="box">
					<h3><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Content Types</h3>
							A <b>content type</b> is the digital representation of a type of item that users will interact with on your site. For example, a "page" is a content type, as is an "article", an "event", a "recipe", and a "product". On the left, you can configure settings for how these items are posted, read, modified, and interacted with.
							<br /><br />
							Each content type can display different data, defined by individual units that we call <b>data fields</b>. With data fields, you can configure a content type to store and display an image, a gallery, a video, a price - the list is endless. Check out the data panel to see examples of what you can do.
							</div>
						</div>Start</h3>
					<div class="box-content">
						<div class="clearboth"></div>
						<div class="two-column-left">
							<h4>Naming</h4>
							<ul class="form-fields">
								
								<li>
									<label>Plural</label>
									<input type="text" class="big-text" name="plural" value="<?=$this->ContentType->getPlural()?>"/>
								</li>
								<li>
									<label>Singular</label>
									<input type="text" class="big-text" name="title" value="<?=$this->ContentType->getTitle()?>"/>
								</li>
								<li>
									<label><a class="tooltip question-mark">?</a><div class="tooltip-content">
										<div class="tooltip-arrow"></div>
										<div class="tooltip-inner">
										<h3>Content Type Permalink</h3>
										The text representing the type in a URL. <br /><br />E.g. "<?=CN_URL?><b><?=Utility::makeUrl($this->ContentType->getPlural())?></b>/"
										</div>
									</div>Permalink</label>
									<p class="field-description"></p>
									<input type="text" class="big-text" name="permalink" value="<?=$this->ContentType->getPermalink()?>"/>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							
							<h4>Miscellaneous</h4>
							<ul class="form-fields">
								<li>
									<label><input type="checkbox" <?php if($this->ContentType->getSearchAppear()) echo 'checked="checked"'; ?> name="search_appear" value="1"/> <b><?=ucwords($this->ContentType->getPlural());?></b> appear in site-wide searches.</label>
								</li>
								<li class="last">
									<label><input type="checkbox" <?php if($this->ContentType->getRequireApproval()) echo 'checked="checked"'; ?> name="require_approval"/> Submitted & edited <b><?=strtolower($this->ContentType->getPlural())?></b> (except for those by global administrators) require approval before appearing</label>
								</li>
							</ul>
							<h4>Permissions</h4>
							<ul class="form-fields">
								<li><label><input <?php if($this->ContentType->getPermNologgedSubmit()) echo 'checked="checked"'?> type="checkbox" name="perm_nologged_submit"/> Non-logged in users can submit a(n) <b><?=strtolower($this->ContentType->getTitle())?></b></label></li>
								<li class="last"><label><input <?php if($this->ContentType->getPermLoggedSubmit()) echo 'checked="checked"'?>  type="checkbox" name="perm_logged_submit"/> Logged-in users can submit a(n) <b><?=strtolower($this->ContentType->getTitle())?></b></label></li>
							</ul>

						</div>
						<div class="clearboth"></div>
						<?php Modulator()->runFunction('content_general_config', $this->ContentType->getId());?>
							
					</div>
				</div>
			</section>
			<section id="data" style="display:none;">
				<div class="box">
					<h3>Data</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Data Fields</h3>
							<b>Data fields</b> are handlers for the submission, storage, and display of information for your <b><?=strtolower($this->ContentType->getPlural())?></b>. They let you add any sort of data you want, from dates to rich-text editing fields to image galleries. To read about the available data field types and download new ones, click <a href="http://concerto.torchdm.com/data-types/" target="_blank">here</a>.
							</div>
						</div>Add Data Field</h4>
							<ul class="form-fields">
								<li>
									<label>Field Name</label>
									<input type="text" class="big-text wide" name="field_display_name"/>
								</li>
								<li>
									<label>Data Type</label>
									<select name="field_data_type" id="data-type">
										<?php dataTypeSelect();?>
									</select>
									
								</li>
								<li>
									<label><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Field Description</h3>
							Here you can provide a clarification of this data field that users will see on the submission form. E.g. "Check this box if you agree to the terms."
							</div>
						</div>Field Description</label>
									
									<textarea name="field_description" class="wide"></textarea>
								</li>
								
								
								<li>
									<label><input type="checkbox" name="required" value="TRUE"/> Require this field when adding a(n) <b><?=strtolower($this->ContentType->getTitle())?></b></label>
								</li>
								<li class="last">
									<button id="add-field" class="small-button">Add Field</button>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Manage your Data Fields</h3>
							Below you can see all of the data fields attached to your <b><?=strtolower($this->ContentType->getPlural())?></b>. You can click on them to change their names and descriptions or to remove them entirely.
							</div>
						</div>Manage Data Fields</h4>
							<?php $this->manageDataTable();?>
						</div>
						<div class="clearboth"></div>
					</div>
				</div>
			</section>
			<section id="interactions" style="display:none;">
				<div class="box">
					<h3><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>User Interactions</h3>
							These settings allow users to interact with individual <b><?=strtolower($this->ContentType->getPlural())?></b>, such as adding them to their favorites, putting them on their wish list, adding them to a shopping cart, etc. You can define the interactions and the text associated with them below.
							</div>
						</div>User Interactions</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4>Add Interaction</h4>
							<ul class="form-fields">
								<li>
									<label>Name (e.g. "Shopping Cart")</label>
									<input class="big-text wide" type="text" name="interaction_name"/>
								</li>
								<li>
									<label>"On" Text (e.g. "Add to Cart")</label>
									<input class="wide" type="text" name="interaction_on_text"/>
								</li>
								<li>
									<label>"On" Alert (e.g. "Added to Cart")</label>
									<input class="wide" type="text" name="interaction_on_alert"/>
								</li>
								<li>
									<label>"Off" Text (e.g. "Remove from Cart")</label>
									<input class="wide" type="text" name="interaction_off_text"/>
								</li>
								<li>
									<label>"Off" Alert (e.g. "Removed from Cart")</label>
									<input class="wide" type="text" name="interaction_off_alert"/>
								</li>
								<li>
									<button class="small-button" id="add-interaction-button">Add Interaction</button>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Manage your Interactions</h3>
							Below you can see all of the interactions permitted with <b><?=strtolower($this->ContentType->getPlural())?></b>. You can click on them to change their names and text or to remove them entirely.
							</div>
						</div>Manage User Interactions</h4>
						<?php $this->manageInteractionsTable();?>
						</div>
						<div class="clearboth"></div>
					</div>
				</div>
			</section>
			<section id="tags" style="display:none;">
				<div class="box">
					<h3><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Tags</h3>
							Tags allow you to categorize your <b><?=strtolower($this->ContentType->getPlural())?></b> by type, subject, or anything else you can think of. You can have an unlimited number of tag groups, which essentially represent the trait that is being categorized, and within each group an unlimited number of tags, which represent the different ways of describing that trait.
							</div>
						</div>Tags</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4>Add Tag</h4>
							<button id="add-tag-tab-button" class="form-tab selected">Add Tag</button><button id="add-tag-group-tab-button" class="form-tab">Add Tag Group</button>
							<div id="add-tag-tab" class="tag-tab">
							<ul class="form-fields">
								<input type="hidden" name="tag_type" value="tag"/>
								<li>
									<label>Tag Name</label>
									<input class="big-text wide" type="text" name="tag_title"/>
								</li>
								<li>
									<label>Tag Permalink</label>
									<input class="wide" type="text" name="tag_permalink"/>
								</li>
								<li>
									<label>Order</label>
									<input type="text" class="thin" name="tag_order"/>
								</li>
								<li>
									<?php 
									$results = DB()->getResults("SELECT `tag_title`, `tag_id` FROM `cn_tags` WHERE `tag_type`='group' AND `tag_content_type`='".$this->ContentType->getId()."'");?>
									<label>Tag Group</label>
									<select name="tag_group" id="tag-group-select">
										<option value="">Select a Group</option>
										
										<?php foreach($results as $tag) : ?>
										<option value="<?=$tag->tag_id?>"><?=$tag->tag_title?></option>
										<?php endforeach;?>
									</select>
								</li>
								<li>
									<input type="submit" id="add-tag" name="add_tag" class="small-button" value="Add Tag"/>
								</li>
							</ul>
							</div>
							<div id="add-tag-group-tab" style="display:none;" class="tag-tab">
							<ul class="form-fields">
								<input type="hidden" name="tag_type" value="group"/>
								<li>
									
									<label>Tag Group Name</label>
									<input class="big-text wide" type="text" name="tag_title"/>
								</li>
								<li>
									<label>Tag Group Permalink</label>
									<input class="wide" type="text" name="tag_permalink"/>
								</li>
								<li>
									<label><input type="radio" name="tag_order" value="name"/> Order tags alphabetically</label>
									<label><input type="radio" name="tag_order" value="custom"/> Order tags by tag order (defined per tag)</label>
								</li>
								<li>
									<input type="submit" id="add-tag-group" name="add_tag_group" class="small-button" value="Add Tag Group"/>
								</li>
							</ul>
							</div>
						</div>
						<div class="two-column-right">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Manage Tags</h3>
							Below you can see all of the tags available for <b><?=strtolower($this->ContentType->getPlural())?></b>, organized by tag group. You can click on them to change their information or to remove them entirely.
							</div>
						</div>Manage Tags</h4>
						<?php $this->manageTagsTable();?>
						</div>
						<div class="clearboth"></div>
					</div>
				</div>
			</section>
			<section id="feedback" style="display:none;">
				<div class="box">
					<h3>User Feedback</h3>
					<div class="box-content">
						<h4>General</h4>
						<ul class="form-fields">
							<li>
								<label><input type="checkbox"<?= ($this->ContentType->getAllowComments()) ? ' checked="checked"' : '';?>id="allow_comments" name="allow_comments"/> Allow comments</label>
							</li>
							<li>
								<label><input type="checkbox"<?= ($this->ContentType->getAllowRatings()) ? ' checked="checked"' : '';?> id="allow_ratings" name="allow_ratings"/> Allow ratings</label>
							</li>
						</ul>
						<h4>Process</h4>
						<p><i>Comments and ratings can either be performed together (i.e., rate and comment at the same time), or separately (for all intents and purposes they are two separate functions)</i></p>
						<ul class="form-fields">
							<li>
								<label><input type="radio"<?= ($this->ContentType->getFeedbackMerge() == 'together') ? ' checked="checked"' : '';?> name="feedback_merge" value="together"/> Together</label>
							</li>
							<li>
								<label><input type="radio"<?= ($this->ContentType->getFeedbackMerge() == 'separate') ? ' checked="checked"' : '';?> name="feedback_merge" value="separate"/> Separately</label>
							</li>
						</ul>
						<h4>Permissions</h4>
						<ul class="form-fields">
							<li>
								<label><input type="radio"<?= ($this->ContentType->getFeedbackPermissions() == 'anyone') ? ' checked="checked"' : '';?> name="feedback_permissions" value="anyone"/> Anyone can submit feedback on <b><?=strtolower($this->ContentType->getPlural())?></b></label>
								</li>
							<li>
								<label><input type="radio"<?= ($this->ContentType->getFeedbackPermissions() == 'logged_in') ? ' checked="checked"' : '';?> name="feedback_permissions" value="logged_in"/> Only logged-in users may submit feedback</label>
							</li>
						</ul>
						<h4>Limitations</h4>
						<p><i>A "user" is determined by IP if not logged in, and by user ID if logged in. </i></p>
						<ul class="form-fields">
							<li>
								<label><input type="checkbox"<?= ($this->ContentType->getRatingsLimit()) ? ' checked="checked"' : '';?> name="ratings_limit"/> Limit users to 1 rating per <b><?=strtolower($this->ContentType->getTitle())?></b></label>
							</li>
							<li>
								<label><input type="checkbox"<?= ($this->ContentType->getCommentsLimit()) ? ' checked="checked"' : '';?> name="comments_limit"/> Limit users to 1 comment per <b><?=strtolower($this->ContentType->getTitle())?></b></label>
							</li>
						</ul>
					</div>
				</div>
			</section>
			<section id="reading" style="display:none;">
				<div class="box">
					<h3>Reading</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Display Order</h3>
							When someone is viewing multiple <b><?=strtolower($this->ContentType->getPlural())?></b>, there is typically an order in which they would want to see them. For example, blog posts could be ordered by date, while recipes could be ordered by title. Select the appropriate display order for <b><?=strtolower($this->ContentType->getPlural())?></b> below.
							
							</div>
						</div>Display Order</h4>
							
							<ul class="form-fields">
								<li>
									<label>Order <b><?=strtolower($this->ContentType->getPlural())?></b> by</label>
									<?php $orderColumn = $this->ContentType->getOrderColumn();?>
									<select name="order_column">
										<option <?=($orderColumn == 'random') ? 'selected="selected"' : ''?> value="random">Random</option>
										<?php $columns = DB()->getResults("SELECT `cf_column`, `cf_display_name` FROM `cn_content_fields` WHERE `cf_content_type`='".$this->ContentType->getId()."' ORDER BY `cf_display_name`");
										?>
										<?php foreach($columns as $column) : ?>
										<option value="<?=$column->cf_column?>" <?=($orderColumn ==	$column->cf_column) ? 'selected="selected"' : ''?>><?=$column->cf_display_name?></option>
										<?php endforeach;?>
									</select>
								</li>
								<li>
									<label>Order Direction</label>
									<select name="order_direction">
										<option <?=($this->ContentType->getOrderDirection() == 'ASC') ? 'selected="selected"' : ''?> value="ASC">Ascending (A-Z, 0-9)</option>
										<option <?=($this->ContentType->getOrderDirection() == 'DESC') ? 'selected="selected"' : ''?> value="DESC">Descending (Z-A, 9-0)</option>
									</select>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Accessibility</h3>
							Turn this on if you want single <b><?=strtolower($this->ContentType->getPlural())?></b> to be inaccessible by URL. They will still be accessible by using <a>initQuery()</a>. This option is useful for light-weight or utility content types like stream activity.
							</div>
						</div>Accessibility</h4>
							<ul class="form-fields">
								<li>	
									<label><input type="checkbox" name="inaccessible_url" value="1" <?php if($this->ContentType->getInaccessibleUrl()) echo 'checked="checked"';?>/> Inaccessible via Unique URL</label>
								</li>
							</ul>
						</div>
						<div class="clearboth"></div>
						<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>RSS</h3>
							Users can also view your content from places other than your site itself, like via RSS. RSS is really simple syndication - it allows for users to view content on your site through their favorite readers. Here you can limit how many <b><?=strtolower($this->ContentType->getPlural())?></b> they see and how much they see of them.
							<br /><br />
							Click <a href="http://www.whatisrss.com" target="_blank">here</a> for more information about RSS.
							</div>
						</div>RSS Settings</h4>
						<h5>General</h5>
						<ul class="form-fields">
							<li>
								<label><input type="checkbox"<?=($this->ContentType->getEnableRss()) ? ' checked="checked"' : ''?> name="enable_rss"/> Enable RSS for <b><?=strtolower($this->ContentType->getPlural())?></b></label>
							</li>
							<li>
								RSS feed shows the <input type="text" class="thin" value="<?=$this->ContentType->getNumRssItems()?>" name="num_rss_items"/> most recent items
							</li>
						</ul>
						<h5>Display</h5>
						<ul class="form-fields">
							<li>
								<label><input type="radio" <?=($this->ContentType->getRssDescription() == 'excerpt') ? ' checked="checked"' : ''?> name="rss_description" value="excerpt"/> RSS content shows the first <input type="text" class="thin" value="<?=$this->ContentType->getNumRssWords()?>" name="num_rss_words"/> words of the main content field</label>
							</li>
							<li>
								<label><input type="radio" <?=($this->ContentType->getRssDescription() == 'whole') ? ' checked="checked"' : ''?> name="rss_description" value="whole"/> RSS content shows entire main content field</label>
							</li>
						</ul>
						

					</div>
				</div>
			</section>
			<section id="relations" style="display:none;">
				<div class="box">
					<h3>Content Relations</h3>
					<div class="box-content">
					<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Geneological Relations</h3>
							These settings affect which content items users can choose in the <b>parent content</b> field when submitting a(n) <b><?=strtolower($this->ContentType->getTitle())?></b>.
							</div>
						</div>Geneological Relations</h4>
					<b><?=ucwords($this->ContentType->getPlural())?></b> <select name="parent_gate"><option <?php if($this->ContentType->getParentGate() == 'can') echo 'selected="selected"'?> value="can">can</option><option <?php if($this->ContentType->getParentGate() == 'must') echo 'selected="selected"'?> value="must">must</option></select> be a child of a(n)
					<ul class="form-fields">
					
					<?php $results = DB()->getResults("SELECT * FROM `cn_content_types`");
						$count = count($results);
						foreach($results as $key=>$result) : ?>
						<?php if($key == ($count - 1)) : ?>
						<li class="last">
						<?php else : ?>
						<li>
						<?php endif;?>
							<label><input type="checkbox" <?php if(in_array($result->ct_id, $this->ContentType->getAllowedParents())) echo 'checked="checked"'?> name="allowed_parents[]" value="<?=$result->ct_id?>"/> <?=ucwords($result->ct_title)?></label>
						</li>
					<?php endforeach;?>
					</ul>
				</div>
			</div>
			</section>
			<section id="permalinks" style="display:none;">
			<div class="box">
				<h3><a class="tooltip question-mark">?</a><div class="tooltip-content">
					<div class="tooltip-arrow"></div>
					<div class="tooltip-inner">
					<h3>Permalink Settings</h3>
					Permalink settings determine how your <b><?=strtolower($this->ContentType->getPlural())?></b> are accessed via the web. They are generated from the tags, data, and other content associated with each individual <b><?=strtolower($this->ContentType->getTitle())?></b>. You can drag around the available structures to build your ideal permalink; some of them have secondary options that can be configured by clicking on the pencil icon.
					
					</div>
				</div>Permalink Settings</h3>
				<div class="box-content">
					<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
					<div class="tooltip-arrow"></div>
					<div class="tooltip-inner">
					<h3>Single Permalinks</h3>
					These permalinks are used to access individual <b><?=strtolower($this->ContentType->getPlural())?></b>. 
					
					</div>
				</div>Single-Content Permalink Structure</h4>
						<ul id="single-permalink-structure" class="permalink-structure">
							<li class="permalink-structure-blank can-sort"></li>
							<?php $permalinkStructures = array();?>
							<?php foreach($this->ContentType->getSinglePermalinkStructure() as $structure) : $permalinkStructures[] = $structure['name']; ?>
								<?php $this->generatePermalinkStructureOption($structure, 'single');?>
							<?php endforeach;?>
							<div class="clearboth"></div>
						</ul>
						
						<ul id="single-permalink-structure-bank" class="permalink-structure-bank">
							<?php if(!in_array('content_type', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('content_type');?>
							<?php endif;?>
							<?php if(!in_array('first_tag', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('first_tag');?>
							<?php endif;?>
							<?php if(!in_array('first_tag_from_group', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('first_tag_from_group');?>
							<?php endif;?>
							<?php if(!in_array('geneology', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('geneology');?>
							<?php endif;?>
							<?php if(!in_array('year', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('year');?>
							<?php endif;?>
							<?php if(!in_array('month', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('month');?>
							<?php endif;?>
							<?php if(!in_array('day', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('day');?>
							<?php endif;?>
							<div class="clearboth"></div>
						</ul>
						<div class="clearboth"></div>
					<?php $tagGroups = DB()->getResults("SELECT `tag_title`, `tag_id`, `tag_permalink` FROM `cn_tags` WHERE `tag_content_type`='".$this->ContentType->getId()."' AND `tag_type`='group' ORDER BY `tag_title`");
					$tagPermalinkStructures = array();
					foreach($this->ContentType->getTagPermalinkStructure() as $structure) {
						$tagPermalinkStructures[$structure['id']] = $structure['structures'];
					}
					
					foreach($tagGroups as $group) : ?>
					<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
					<div class="tooltip-arrow"></div>
					<div class="tooltip-inner">
					<h3>Tag Permalinks</h3>
					These permalinks are used to browse <b><?=strtolower($this->ContentType->getPlural())?></b> with certain tags. Note that you can have a separate structure for each tag group.
					
					</div>
				</div>Tag Permalink Structure (<?=$group->tag_title?>)</h4>
						<ul id="tag-group-<?=$group->tag_id?>-permalink-structure" class="permalink-structure tag-group-permalink-structure" data-group-id="<?=$group->tag_id?>">
							<li class="permalink-structure-blank can-sort"></li>
							<?php $permalinkStructures = array();?>
							<?php foreach($tagPermalinkStructures[$group->tag_id] as $structure) : $permalinkStructures[] = $structure['name']; ?>
								<?php $this->generatePermalinkStructureOption($structure, 'tag');?>
							<?php endforeach;?>
							<div class="clearboth"></div>
						</ul>
						
						<ul id="tag-group-<?=$group->tag_id?>-permalink-structure-bank"  class="permalink-structure-bank tag-group-permalink-structure-bank" >
							<?php if(!in_array('content_type', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('content_type');?>
							<?php endif;?>
							<?php if(!in_array('first_tag_from_other_group', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('first_tag_from_other_group', null, $group->tag_id);?>
							<?php endif;?>
							<?php if(!in_array('geneology', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('geneology');?>
							<?php endif;?>
							<div class="clearboth"></div>
						</ul>
					<?php endforeach;?>
				
					<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
					<div class="tooltip-arrow"></div>
					<div class="tooltip-inner">
					<h3>Browsing Permalinks</h3>
					These permalinks are used to browse <b><?=strtolower($this->ContentType->getPlural())?></b> in general.					
					</div>
				</div>Browsing Permalink Structure</h4>
						<ul id="browsing-permalink-structure" class="permalink-structure">
							<li class="permalink-structure-blank can-sort"></li>
							<?php $permalinkStructures = array();?>
							<?php foreach($this->ContentType->getBrowsingPermalinkStructure() as $structure) : $permalinkStructures[] = $structure['name']; ?>
								<?php $this->generatePermalinkStructureOption($structure, 'browsing');?>
							<?php endforeach;?>
							<div class="clearboth"></div>
						</ul>
						<ul id="browsing-permalink-structure-bank" class="permalink-structure-bank">
							<?php if(!in_array('content_type', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('content_type');?>
							<?php endif;?>
							<?php if(!in_array('geneology', $permalinkStructures)): ?>
							<?php $this->generatePermalinkStructureOption('geneology');?>
							<?php endif;?>
						</ul>
						<div class="clearboth"></div>
					
				</div>
			</div>
			</section>
			</form>
			
			
		</div>
		<div class="clearboth"></div>
	
		
		
		<?php
	}
	
	protected function generatePermalinkStructureOption($structure, $type = null, $group = null) {
		if(!is_array($structure)) $structure = array('name'=>$structure);
		switch($structure['name']) {
			case 'content_identifier':
				?>
				<li data-structure="content_identifier">Content Identifier<a data-structure-name="Content Identifier" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label><input type="radio" name="option" value="id" <?php if($structure['option'] == 'id') echo 'checked="checked"';?>/> Content ID</label>
					<label><input type="radio" name="option" value="title" <?php if($structure['option'] == 'title') echo 'checked="checked"';?>/> Content Title</label>
				</div></li>
				<?php
				break;
			case 'content_type':
				?>
				<li <?php if($type != 'browsing') echo 'class="can-sort"';?> data-structure="content_type"><b><?=$this->ContentType->getPermalink()?></b></li>
				<?php
				break;
			case 'tag_name':
				?>
				<li <?php if($type != 'tag') echo 'class="can-sort"';?> data-structure="tag_name">Tag Name</li>
				<?php
				break;
			case 'first_tag':
				?>
				<li class="can-sort" data-structure="first_tag">First Tag</li>
				<?php
				break;
			case 'day':
				?>
				<li class="can-sort" data-structure="day">Day</li>
				<?php
				break;
			case 'first_tag_from_group':
				$tagGroups = DB()->getResults("SELECT `tag_title`, `tag_id`, `tag_permalink` FROM `cn_tags` WHERE `tag_content_type`='".$this->ContentType->getId()."' AND `tag_type`='group' ORDER BY `tag_title`");
				if(count($tagGroups) > 1) : 
				?>
				<li class="can-sort" data-structure="first_tag_from_group">First Tag From Group<a data-structure-name="First Tag From Group" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label>Choose Tag Group</label>
					<select name="option">
						<?php foreach($tagGroups as $group) : ?>
							<option <?php if($structure['option'] == $group->tag_id) echo 'selected="selected"';?> value="<?=$group->tag_id?>"><?=$group->tag_title?></option>
						<?php endforeach;?>
					</select>
				</div></li>
				<?php
				endif;
				break;
			case 'first_tag_from_other_group':
				$tagGroups = DB()->getResults("SELECT `tag_title`, `tag_id`, `tag_permalink` FROM `cn_tags` WHERE `tag_content_type`='".$this->ContentType->getId()."' AND `tag_type`='group' AND `tag_id` != '$group' ORDER BY `tag_title`");
				if(count($tagGroups) > 1) : 
				?>
				<li class="can-sort" data-structure="first_tag_from_group">First Tag From Other Group<a data-structure-name="First Tag From Other Group" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label>Choose Tag Group</label>
					<select name="option">
						<?php foreach($tagGroups as $group) : ?>
							<option <?php if($structure['option'] == $group->tag_id) echo 'selected="selected"';?> value="<?=$group->tag_id?>"><?=$group->tag_title?></option>
						<?php endforeach;?>
					</select>
				</div></li>
				<?php
				endif;
				break;
			case 'year':
				?>
				<li class="can-sort" data-structure="year">Year</li>
				<?php
				break;
			case 'geneology':
				?>
				<li class="can-sort" data-structure="geneology">Geneology<a data-structure-name="Geneology" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<p>The geneology structure renders all ancestors (set by using the Parent Content field) of the current <b><?=$this->ContentType->getTitle()?></b></p>
					<label><input type="radio" name="option" value="parent" <?php if($structure['option'] == 'parent') echo 'checked="checked"';?>/> All Ancestors up to Parent</label>
					<label><input type="radio" name="option" value="grandparent" <?php if($structure['option'] == 'grandparent') echo 'checked="checked"';?>/> All Ancestors up to Grandparent</label>
				</div></li>
				<?php
				break;
			case 'month':
				?>
				<li class="can-sort" data-structure="month">Month<a data-structure-name="Month" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label><input type="radio" name="option" value="three-letter" <?php if($structure['option'] == 'three-letter') echo 'checked="checked"';?>/> Three-Letter Representation</label>
					<label><input type="radio" name="option" value="full" <?php if($structure['option'] == 'full') echo 'checked="checked"';?>/> Full Name</label>
				</div></li>
				<?php
				break;
				
		}
	}
}
?>